﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vds2465Telegrams;

namespace Vds2465Parser
{
	internal static class GenParse_UserData_74_Container
	{
		#region private constants

		private const int NrOfBytesWithoutBusBytes = 4;

		#endregion private constants

		#region internal methods

		internal static byte[] GenerateBytes(UserData userData)
		{
			byte[] userDataBytes = null;
			if (userData is UserData_74_Container)
			{
				UserData_74_Container userData74 = userData as UserData_74_Container;

				byte[] busBytes = userData74.GetCopyOfBytes();
				int nrOfBusBytes = 0;
				if (busBytes != null)
				{
					nrOfBusBytes = busBytes.Length;
				}
				byte nrOfTotalBytes = (byte)(NrOfBytesWithoutBusBytes + nrOfBusBytes);

				userDataBytes = new byte[nrOfTotalBytes];
				userDataBytes[0] = (byte)(nrOfTotalBytes - GenParse_UserData.HeaderLength);	// user data length
				userDataBytes[1] = UserData.UserData74Container;
				userDataBytes[2] = userData74.Device;
				userDataBytes[3] = userData74.BusType;
				if (busBytes != null)
				{
					for (int index = 0; index < busBytes.Length; index++)
					{
						userDataBytes[NrOfBytesWithoutBusBytes + index] = busBytes.ElementAt(index);
					}
				}
			}
			else
			{
				// TODO handle error - wrong UserData type
			}

			return userDataBytes;
		}

		internal static bool ParseBytes(byte[] userDataBytes, out UserData userData74Container, out int consumedBytes)
		{
			consumedBytes = 0;
			userData74Container = null;

			if (userDataBytes.Length >= NrOfBytesWithoutBusBytes)
			{
				byte setLength = userDataBytes[0];
				if (userDataBytes.Length >= setLength + 2)
				{
					if (userDataBytes[0] > 0)
					{
						// first byte                
						if (userDataBytes[1] == UserData.UserData74Container)
						{
							byte device = userDataBytes[2];
							byte busType = userDataBytes[3];

							byte nrOfBusBytes = (byte)(userDataBytes[0] - 2);	// we need to subtract the device byte
							byte[] busBytes = new byte[nrOfBusBytes];
							for (int index = 0; index < nrOfBusBytes; index++)
							{
								busBytes[index] = userDataBytes[NrOfBytesWithoutBusBytes + index];
							}

							userData74Container = new UserData_74_Container(device, busType, busBytes);
							consumedBytes = NrOfBytesWithoutBusBytes + nrOfBusBytes;
							return true;
						}

						// wrong value for the data type
						return false;
					}				

					// TODO handle error (wrong value in first byte the length)
					return false;
				}

				// TODO handle error: not enough bytes as specified by the SL value
				return false;
			}

			// TODO handle error (not enough bytes)
			return false;
		}

		#endregion internal methods
	}
}
